import 'dart:async';
import 'package:flutter/material.dart';
import 'package:metaera_flutter/utils/Device.dart';
import 'package:metaera_flutter/utils/Font.dart';
import 'package:metaera_flutter/utils/Color.dart';
import 'package:metaera_flutter/widgets/tabbar.dart';
import 'package:metaera_flutter/widgets/NavigationView.dart';
import 'pages/home/HomePage.dart';
import 'pages/kuaixun/kuaixunPage.dart';
import 'pages/search/SearchPage.dart';
import 'pages/mine/MinePage.dart';
import 'pages/zhuanlan/ZhuanlanPage.dart';
import 'services/share_service.dart';

class MainContainer extends StatefulWidget {
  const MainContainer({super.key});

  @override
  State<MainContainer> createState() => _MainContainerState();
}

class _MainContainerState extends State<MainContainer> {
  int _currentIndex = 0;

  // 页面列表
  late final List<Widget> _pages;

  // 页面标题列表
  final List<String> _pageTitles = ['首页', '快讯', '专栏', '搜索', '我的'];

  // 搜索框提示文本
  final List<String> _hintTexts = [
    '链游Illuvium完成1000万',
    '探索最新的区块链游戏',
    '获取行业前沿资讯',
    '了解NFT市场动态',
    '发现优质GameFi项目',
  ];

  int _currentHintIndex = 0;
  Timer? _hintTextTimer;

  @override
  void initState() {
    super.initState();
    _initializePages();
    _startHintTextTimer();
  }

  void _initializePages() {
    _pages = [
      const HomePage(),
      const CategoryPage(),
      const ZhuanlanPage(),
      const SearchPage(),
      const ProfilePage(),
    ];
  }

  // 启动提示文本切换定时器
  void _startHintTextTimer() {
    _hintTextTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      if (mounted) {
        setState(() {
          _currentHintIndex = (_currentHintIndex + 1) % _hintTexts.length;
        });
      }
    });
  }

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  // 处理logo点击事件，分享到微信
  void _onLogoTapped() {
    ShareService.instance.showShareDialog(
      context,
      const ShareContent(
        title: 'MetaEra - 区块链游戏资讯平台',
        content: '发现最新的区块链游戏资讯，探索GameFi世界的无限可能！',
        url: 'https://metaera.com',
        imageUrl: 'https://metaera.com/logo.png',
      ),
    );
  }

  // 构建通用导航栏
  PreferredSizeWidget _buildNavigationAppBar() {
    // 如果是首页，显示搜索AppBar
    if (_currentIndex == 0) {
      return _buildSearchAppBar();
    }

    // 其他页面显示NavigationView
    return NavigationView(
      title: _pageTitles[_currentIndex],
      type: 'home', // 设置为home类型，不显示返回按钮
      actions: _buildAppBarActions(),
    );
  }

  // 构建AppBar的actions
  List<Widget>? _buildAppBarActions() {
    switch (_currentIndex) {
      case 3: // 搜索页面
        return [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              // 可以在这里添加搜索功能
            },
          ),
        ];
      default:
        return null;
    }
  }

  // 构建搜索AppBar
  PreferredSizeWidget _buildSearchAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      automaticallyImplyLeading: false,
      title: Container(
        height: DeviceUtils.width36,
        decoration: BoxDecoration(
          color: const Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Row(
          children: [
            Padding(
              padding: EdgeInsets.only(
                left: DeviceUtils.width12,
                right: DeviceUtils.width6,
              ),
              child: Image.asset(
                'assets/images/base/search.png',
                width: DeviceUtils.width14,
                height: DeviceUtils.width14,
              ),
            ),
            Expanded(
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    _currentIndex = 3; // 跳转到搜索页面
                  });
                },
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    _hintTexts[_currentHintIndex],
                    style: TextStyle(
                      fontSize: AppFonts.fontSize14,
                      color: AppColors.color9C9C9C,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      leading: Padding(
        padding: EdgeInsets.only(left: DeviceUtils.width16),
        child: GestureDetector(
          onTap: _onLogoTapped,
          child: SizedBox(
            child: Image.asset(
              'assets/images/base/logo_cai.png',
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),
      actions: [
        Padding(
          padding: EdgeInsets.only(right: DeviceUtils.width16),
          child: GestureDetector(
            onTap: _onLogoTapped,
            child: Image.asset(
              'assets/images/base/placeholder_mine.png',
              width: DeviceUtils.width36,
              height: DeviceUtils.width36,
            ),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    _hintTextTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildNavigationAppBar(),
      body: IndexedStack(index: _currentIndex, children: _pages),
      bottomNavigationBar: Tabbar(
        currentIndex: _currentIndex,
        onTap: _onTabTapped,
      ),
    );
  }
}
